import Vue from 'vue'
const api = window.$api.organization.department

let DepartmentLoadTimer = null // 加载用户信息定时器
const DepartmentLoadings = []  // 需要加载的用户信息

const Department = {
    namespaced: true,
    state:{
        updateList:{},
        map:{},
        one:{}
    },
    actions:{
        async loadList({ commit,state},{companyId,isCache}){
            if(!state.updateList[companyId] || !isCache){
                state.updateList[companyId] = true
                var res = await api.getList(companyId)
                const data = res.data.data
                commit('SET_DEPARTMENT_MAP', {companyId,list:data})
            }
        },
        async load({ commit,state},{departmentId,isNotTime}){
            if(isNotTime){
                if(!state.updateList[departmentId]){
                    state.updateList[departmentId] = true
                    const req = departmentId
                    var res = await api.getDepartments(req)
                    const data = res.data.data
                    data.forEach(item=>{
                        commit('SET_DEPARTMENT_ONE', {departmentId:item.f_DepartmentId,entity:item})
                    })
                }
            }
            else {
                if(!state.updateList[departmentId]){
                    state.updateList[departmentId] = true
                    DepartmentLoadings.push(departmentId)
                    // 50ms 内只执行一次
                    if(DepartmentLoadings.length > 0 && !DepartmentLoadTimer){
                        DepartmentLoadTimer = setTimeout(async ()=>{
                            if(DepartmentLoadings.length > 0){
                                const req = String(DepartmentLoadings)
                                DepartmentLoadings.length = 0
    
                                var res = await api.getDepartments(req)
                                const data = res.data.data
                                data.forEach(item=>{
                                    commit('SET_DEPARTMENT_ONE', {departmentId:item.f_DepartmentId,entity:item})
                                })
                            }
                            DepartmentLoadTimer = null
                        }, 50)
                    }
                }
            }
        }
    },
    mutations:{
        SET_DEPARTMENT_MAP: (state, payload) => {
            Vue.set(state.map,payload.companyId,payload.list)
        },
        SET_DEPARTMENT_ONE:(state, payload) => {
            Vue.set(state.one,payload.departmentId,payload.entity)
        },
    }
}

export default Department